package com.ldu.houserent.controller.backend;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ldu.houserent.common.base.BaseController;
import com.ldu.houserent.common.dto.JsonResult;
import com.ldu.houserent.common.util.PageUtil;
import com.ldu.houserent.entity.Mark;
import com.ldu.houserent.service.HouseService;
import com.ldu.houserent.service.MarkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Objects;

/**
 * 我的收藏查询和取消收藏控制器
 */
@Controller("backMarkController")
public class MarkController extends BaseController {

    @Autowired
    private HouseService houseService;
    @Autowired
    private MarkService markService;

    /*
        我的收藏列表
     */
    @RequestMapping("/admin/mark")
    public String markList(@RequestParam(value = "page",defaultValue = "1")Long pageNumber, @RequestParam(value = "size",defaultValue = "6")Long pageSize, Model model){
        Page page= PageUtil.initMpPage(pageNumber,pageSize);        //翻页功能
        Mark condition = new Mark();
        condition.setUserId(getLoginUserId());      //获取当前登录用户
        Page<Mark> markPage = markService.findAll(page,condition);       //查询
        for (Mark mark:markPage.getRecords()){      //遍历收藏记录
            mark.setHouse(houseService.get(mark.getHouseId()));         //将房屋的信息放到每一条记录中
        }
        model.addAttribute("pageInfo",markPage);
        model.addAttribute("tab","mark-list");         //鼠标点击后，改变页面中的字体颜色样式
        model.addAttribute("pagePrefix","/admin/mark?");       //实现翻页
        return "admin/mark-list";       //指向了jsp包下的admin包下的mark-list.jsp页面
    }//markList

    /*
        取消收藏
     */
    @RequestMapping(value = "/admin/mark/cancel",method = RequestMethod.POST)
    @ResponseBody
    public JsonResult cancelMark(@RequestParam("id")Long id){
        Mark mark = markService.get(id);        //获取到该条收藏记录
        if (mark==null || !Objects.equals(mark.getUserId(),getLoginUserId())){
            return JsonResult.error("取消收藏失败");
        }
        markService.delete(id);     //根据id，删除该条记录
        return JsonResult.success("取消收藏成功");

    }

}
